package com.refusea.train.mapper

import com.refusea.train.domain.entity.ReferrerCommission
import com.refusea.train.domain.req.ReferrerCommissionReq
import com.refusea.train.domain.vo.CommissionStat
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Select
import org.apache.ibatis.annotations.Update
import java.time.LocalDate
import java.time.LocalDateTime

/**
 * @author Zhang Yan 2024/4/25
 **/
@Mapper
interface ReferrerCommissionMapper {

    @Select("select max(ot) from referrer_commission were referrer_id = #{refererId} and cat=#{cat}")
    fun maxOt(refererId: Int, cat: ReferrerCommission.Cat): LocalDateTime?

    @Insert(
        """
        <script>
        insert into referrer_commission 
        (school_id, referrer_id, cat, user_id, order_id, commission, paid, ot)
        values 
        <foreach collection="commissions" item="e" separator=",">
            (#{e.schoolId}, #{e.referrerId}, #{e.cat}, #{e.userId}, #{e.orderId}, #{e.commission}, #{e.paid}, #{e.ot})
        </foreach>
        </script>        
        """
    )
    fun inserts(commissions: List<ReferrerCommission>)

    @Select("<script>SELECT count(*) FROM referrer_commission WHERE ${ORDER_CONDITION}</script>")
    fun count(req: ReferrerCommissionReq): Int

    @Select("<script>SELECT * FROM referrer_commission WHERE $ORDER_CONDITION order by id desc limit #{offset}, #{limit}</script>")
    fun query(req: ReferrerCommissionReq): List<ReferrerCommission>


    @Update("UPDATE referrer_commission SET paid = 1 WHERE school_id = #{schoolId} and id = #{id} and ct < #{date}")
    fun markPaid(schoolId: Int, id: Int, date: LocalDate)

    @Select(
        """
        SELECT sum(commission) commission, cat, paid FROM referrer_commission WHERE referrer_id = #{id}
        group by cat, paid
        """
    )
    fun stat(id: Int): List<CommissionStat>

    @Select("select max(ot) from referrer_commission where referrer_id=#{id} and paid=1")
    fun lastPt(id: Int): LocalDateTime?

    companion object {
        const val ORDER_CONDITION = """
        school_id = #{schoolId}
        <if test='start!=null'>and ct >= #{start}</if>
        <if test='end!=null'>and ct &lt; #{end}</if>
        <if test='referrerId!=null and referrerId!=0'>and referrer_id = #{referrerId}</if>
        <if test='paid!=null'>and paid=#{paid}</if>
        <if test='cat!=null'>and cat=#{cat}</if>
        """
    }
}
